<template>
  <div style="padding: 2px 20px;background-color: #fff;width: 99%;margin: 5px auto 0px">
    <DynamicForm :labelWidth="85" style="margin-top: 20px;" :searchloading="loading" :items="items" v-model="formModel" @onFinish="submit">
    </DynamicForm>
    <div style="margin-top: 20px;">
      <ElTableWithColumns
        :operateColProps="{ width: 200 }"
        @onChange="onChange"
        :loading="loading"
        :data="tableData"
        :columns="columns"
        :pagerInfo="pagerInfo"
      >
        <template #operate="{row}">
          <el-space>
            <el-tag type="primary" style="cursor: pointer;margin-left:2px;" v-hasPermi="['payment:task:query']" @click="() => viewDetail(row)"
              >详情</el-tag
            >
            <el-upload
              v-model:file-list="row.fileList"
              :action="uploadFileUrl"
              :headers="headers"
              :limit="1"
              :show-file-list="false"
              :before-upload="file => beforeUpload(file, row)"
              :on-success="(res, file, files) => uploadSuccess(res, file, files, row)"
              :on-error="(err, file, files) => uploadError(err, file, files, row)"
            >
              <el-tag type="success" style="cursor: pointer;margin-left:2px;">上传业务确认单</el-tag>
            </el-upload>
            <el-tag
              type="success"
              style="cursor: pointer;margin-left:2px;"
              v-hasPermi="['payment:taskEnroll:successlist']"
              @click="() => approval(row)"
              >子项目交付审核
            </el-tag>
          </el-space>
        </template>
      </ElTableWithColumns>
    </div>
    <Detail :openCheck="openDetailCheck" @dialogClose="dialogClose2" :item="item"></Detail>
    <SubTaskApproval v-model="open" :item="item"></SubTaskApproval>
  </div>
</template>

<script lang="ts" setup>
import DynamicForm from '@/components/DynamicForm/index.vue';
import { getTaskList, taskEditInfo } from '@/api/projectMgt/index';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { taskStatusOptions, taskTypeOptions, businessTypeOptions } from '../projectList/utils.ts'
import useDictUtilsStore from '@/store/modules/dict_utils'
import { ActionEnum, type TaskInfo } from '../types'
import useUserStore from '@/store/modules/user'
import Detail from "@/views/project/proSel/detail/index.vue"
import SubTaskApproval from "./subTaskApproval/index.vue"
const baseUrl = import.meta.env.VITE_APP_BASE_API;
import { globalHeaders } from "@/utils/request";
const headers = ref(globalHeaders());
const fileList = ref<UploadFile[]>([]);
const uploadFileUrl = ref(baseUrl + "/resource/oss/upload"); // 上传文件服务器地址
const pagerInfo = reactive({
  pageSize: 10,
  total: 0,
  pageNum: 1
})


const action = ref<ActionEnum>(ActionEnum.PROJECT_ADD)

const title = ref<string>('创建项目')

const { getlabel } = useDictUtilsStore()
const item = ref({})
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const openDetailCheck = ref(false);
const open = ref(false)

/**
 * 业务类型
*/
const businessTypeOptions = proxy?.useDict("wxfe_bus_type").wxfe_bus_type

/**
 * 接单类型
*/
const taskTypeOptions = computed(() => {
  const list = proxy?.useDict("task_type").task_type
  return list
})

/**
 * 项目状态
*/
const taskStatusOptions = computed(() => {
  const list = proxy?.useDict("task_status").task_status
  return list
})


const dialogClose2  = (params:any)=>{
    openDetailCheck.value = false;
}

const viewDetail = (row: TaskInfo) => {
  openDetailCheck.value = true;
  item.value = row;
  // router.push (`/project/projectDetail?id=${row.id}`)
}

/**
 * 上下架
*/
const proStatusoptions = proxy?.useDict("pro_status").pro_status


const router = useRouter()
const loading = ref(false)

const tableData = ref([])

const approval = row => {
  open.value = true;
  item.value = row;
  // router.push (`/project/subTaskApproval?id=${row.id}`)
}


const columns = [
  {
    title: '创建时间',
    dataIndex: 'addTime',
    width: 160
  },
  {
    title: '企业名称',
    dataIndex: 'merchantName',
    width: 160
  },
  {
    title: '服务商名称',
    dataIndex: 'gsmc',
    width: 220
  },
  {
    title: '项目编号',
    dataIndex: 'no',
    width: 140
  },
  {
    title: '项目标题',
    dataIndex: 'name'
  },
  {
    title: '服务金额（元）',
    dataIndex: 'taskCode',
    renderText: (row: TaskInfo) => {
      const {costMax,classify} = row
      if(classify == 1){
        return proxy?.convertFenToYuan(row.cost) +" ~ "+ proxy?.convertFenToYuan(row.costMax);
      }else{
        return `${proxy?.convertFenToYuan(row.cost)}`
      }
    },
    width: 150
  },
  {
    title: '接单类型',
    dataIndex: 'classify',
    width: 100,
    renderText: row => {
         return getlabel('task_type', row.classify)
    }
  },
  {
    title: '业务类型',
    dataIndex: 'busType',
    width: 100,
    renderText: row => {
         return getlabel('wxfe_bus_type', row.busType)
    }
  },
  {
    title: '项目状态',
    dataIndex: 'taskStatus',
    width: 120,
    renderText: row => {
         return getlabel('task_status', row.taskStatus)
    }

  },
  {
    title: '上架状态',
    dataIndex: 'status',
    width: 100,
    renderText: row => {
      console.log('row11', row, proStatusoptions);

         return getlabel('pro_status', row.status)
    }
  },
]
const formModel = ref({})


const items = computed(() => {
  return [
    { prop: 'addTime1', label: '创建时间', valueType: 'date', fieldProps: { type: 'daterange' , valueFormat: 'YYYY-MM-DD','start-placeholder':"开始日期",'end-placeholder':"结束日期"   } },
    { prop: 'no', label: '项目编号', valueType: 'input' , fieldProps: {placeholder:"请输入项目编号"}},
    { prop: 'name', label: '项目标题', valueType: 'input' , fieldProps: {placeholder:"请输入项目标题"} },
    { prop: 'taskStatus', label: '项目状态', valueType: 'select', options: taskStatusOptions.value , fieldProps: {placeholder:"请选择项目状态"}},
    { prop: 'calssify', label: '接单类型', valueType: 'select', options: taskTypeOptions?.value , fieldProps: {placeholder:"请选择接单类型"}},
  ]
})



const query = async (formData = {}) => {
  loading.value = true
  let defaultProvider = useUserStore().defaultProvider;

  const submitData = {
    sydId: 1,
    ...formData,
    ...pagerInfo
  }

  if( formData.addTime1 && formData.addTime1.length > 1 ){
      submitData.beginDate = formData.addTime1[0];
      submitData.endDate = formData.addTime1[1];
  }
  submitData.sydId = defaultProvider.sydId;

  const { response } = await useRequest('/payment/task/list', 'get', {
    params: submitData
  }, { immediate: true })


  console.log('response', response.value);

    if (response.value.code === HttpStatus.SUCCESS) {
      tableData.value = response?.value?.rows
      pagerInfo.total = response.value?.total
    }
    loading.value = false
}
const uploadRef = ref<ElUploadInstance>();
const loadingDialog = ref<boolean>(false);
const fileType = ref([]);
const fileSize = ref(5);
// 移除 employmentContractFormRef 校验
const beforeUpload = (file: UploadRawFile, row?: any) => {
  // 不校验文件类型
  // 校检文件大小
  if (fileSize.value) {
    const isLt = file.size / 1024 / 1024 < fileSize.value;
    if (!isLt) {
      proxy?.$modal.msgError(`上传文件大小不能超过 ${fileSize.value} MB!`);
      return false;
    }
  }
  loadingDialog.value = true;
  return true;
};

const uploadSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles, row?: any) => {
  loadingDialog.value = false;
  if (row && row.fileList) row.fileList = [];
  if (response.code === 200) {
    // proxy?.$modal.msgSuccess("上传成功！");
    const data:any = response.data;
    taskEditInfo({
      id: row.id,
      url: data.url,
      ossId: data.ossId,
      busType:row.busType,
      name: row.name,
      industry: getIndustry(row.industry, 1),
      industryName: getIndustry(row.industryName, 1),
      classify: row.classify,
      gsmc: row.gsmc,
      sydName: row.gsmc,
      sydNo:row.sydNo,
      sydId: row.sydId,
      merchantName: row.merchantName,
      merNo:row.merNo,      
      merId: row.merId,
      proContent: row.proContent,
      cost: row.cost,
      limitNum: row.limitNum,
      no: row.no,
      taskCode: row.taskCode,
      taskStatus: row.taskStatus,
      costMax: row.costMax,
      taskType: row.taskType,
      taskId: row.id,
      opId: row.opId,
      opName: row.opName,
      addTime: row.addTime,
      updateTime: row.updateTime,
      opVerifyBy: row.opVerifyBy,
      opVerifyName: row.opVerifyName,
      opVerifyTime: row.opVerifyTime,
      verifyStatus: row.verifyStatus,      
      status: row.status
    }).then(res => {
      if (res.code === HttpStatus.SUCCESS) {
        proxy?.$modal.msgSuccess("业务确认单上传成功");
      } else {
        proxy?.$modal.msgError(res.msg || "业务确认单上传失败");
      }
    });
    // 可在此处刷新列表或处理 row 数据
    query();
  } else {
    proxy?.$modal.msgError(response.msg || "上传失败");
  }
};
const getIndustry = (industry, tag) => {
  if (!industry) {
    return '--';
  }
  let ids = industry.split(",")
  if (tag == 1) {
    return ids[0];
  } else if (tag == 2) {
    return ids[1];
  }
}
const uploadError = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles, row?: any) => {
  loadingDialog.value = false;
  if (row && row.fileList) row.fileList = [];
  proxy?.$modal.msgError("上传失败");
};
const onChange = ({data, type}) => {
  if (type === 'pageNo') {
    pagerInfo.pageNum = data
  }
  if (type === 'pageSize') {
    pagerInfo.pageSize = data
  }
  query()
}

const submit = data => {
  query(data)
}

onMounted(() => {
  query()
})
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
